package com.csii.security;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.csii.security.authentication.mobile.SmsSend;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


/**
 * 发送短信验证码，阿里短信服务接口
 * @Auther: ian
 */
@Slf4j
@Component
public class AliSmsCodeSender implements SmsSend {

    /**
     * @param mobile 手机号
     * @param content 发送的内容: 接收的是验证码
     * @return
     */
    @Override
    public boolean sendSms(String mobile, String content) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4FmLh4dWyRwAFpFENPjy", "wOPhnA3njFmwjtK8swlt18sgCEqsxw");
        IAcsClient client = new DefaultAcsClient(profile);
        /**
         * accessKeyId: LTAI4FmLh4dWyRwAFpFENPjy
         *       accessKeySecret: wOPhnA3njFmwjtK8swlt18sgCEqsxw
         *       SignName: \u79D1\u84DD\u91D1\u4FE1
         *       TemplateCode: SMS_180340860
         */
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", "科蓝金信");
        request.putQueryParameter("TemplateCode", "SMS_180340860");
        Map<String,String> com=new HashMap<>();
        com.put("code",content);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(com));
        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info(response.toString());
        } catch (ClientException e) {
            log.error(e.getErrMsg());
        }
        return true;
    }

    public static void main(String[] args) {
        //规避缺陷：硬编码手机号码
//        new AliSmsCodeSender().sendSms("13418456639","123333");
    }
}
